import request from '../utils/request'
import type { AxiosResponse } from 'axios'
import type { ApiResponse, PaginationParams } from './user'

export interface ProductItem {
    id: number
    title: string
    price: number
    status: number | string
    images: string[]
    description: string
    createdAt: string
    viewCount: number
    categoryId?: number
    categoryName?: string
    userId?: number
    userName?: string
    schoolId?: number
    schoolName?: string
    [key: string]: any
}

export interface ProductFilter {
    categoryId?: number | string
    minPrice?: number | string
    maxPrice?: number | string
    status?: string
    schoolId?: number | string
    userId?: number | string
    keyword?: string
}

/**
 * 获取商品列表
 * @param params 商品过滤参数和分页参数
 * @returns Promise<ApiResponse<{ content: ProductItem[], totalElements: number }>>
 */
export async function getProducts(params: PaginationParams & ProductFilter = {}): Promise<ApiResponse<{ content: ProductItem[], totalElements: number }>> {
    return request.get<ApiResponse<{ content: ProductItem[], totalElements: number }>>('/product', { params })
}

/**
 * 获取用户商品列表
 * @param params 分页参数和过滤条件
 * @returns Promise<ApiResponse<{ content: ProductItem[], totalElements: number }>>
 */
export async function getUserProducts(params: PaginationParams & { status?: string, userId?: number | string } = {}): Promise<ApiResponse<{ content: ProductItem[], totalElements: number }>> {
    const apiParams = { ...params };

    // 如果没有指定userId，则使用当前登录用户的ID
    if (!apiParams.userId) {
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
        apiParams.userId = userInfo.id;
    }

    return request.get<ApiResponse<{ content: ProductItem[], totalElements: number }>>('/user/products', {
        params: apiParams
    });
}

/**
 * 获取商品详情
 * @param id 商品ID
 * @returns Promise<ApiResponse<ProductItem>>
 */
export async function getProductById(id: number | string): Promise<ApiResponse<ProductItem>> {
    return request.get<ApiResponse<ProductItem>>(`/product/${id}`)
}

/**
 * 创建商品
 * @param data 商品数据
 * @returns Promise<ApiResponse<ProductItem>>
 */
export async function createProduct(data: Omit<ProductItem, 'id' | 'createdAt' | 'viewCount'>): Promise<ApiResponse<ProductItem>> {
    return request.post<ApiResponse<ProductItem>>('/product', data)
}

/**
 * 更新商品
 * @param id 商品ID
 * @param data 商品数据
 * @returns Promise<ApiResponse<ProductItem>>
 */
export async function updateProduct(id: number | string, data: Partial<ProductItem>): Promise<ApiResponse<ProductItem>> {
    return request.put<ApiResponse<ProductItem>>(`/product/${id}`, data)
}

/**
 * 删除商品
 * @param id 商品ID
 * @returns Promise<ApiResponse<null>>
 */
export async function deleteProduct(id: number | string): Promise<ApiResponse<null>> {
    return request.delete<ApiResponse<null>>(`/product/${id}`)
}

/**
 * 更新商品状态
 * @param id 商品ID
 * @param status 商品状态 (1-在售, 2-已售出, 3-已下架, 4-草稿箱)
 * @returns Promise<ApiResponse<ProductItem>>
 */
export async function updateProductStatus(id: number | string, status: number | string): Promise<ApiResponse<ProductItem>> {
    return request.put<ApiResponse<ProductItem>>(`/product/${id}/status`, { status })
}

/**
 * 获取推荐商品
 * @param params 分页参数
 * @returns Promise<ApiResponse<{ content: ProductItem[], totalElements: number }>>
 */
export async function getRecommendedProducts(params: PaginationParams = {}): Promise<ApiResponse<{ content: ProductItem[], totalElements: number }>> {
    return request.get<ApiResponse<{ content: ProductItem[], totalElements: number }>>('/product/recommended', { params })
}

/**
 * 获取相似商品
 * @param id 商品ID
 * @param params 分页参数
 * @returns Promise<ApiResponse<{ content: ProductItem[], totalElements: number }>>
 */
export async function getSimilarProducts(id: number | string, params: PaginationParams = {}): Promise<ApiResponse<{ content: ProductItem[], totalElements: number }>> {
    return request.get<ApiResponse<{ content: ProductItem[], totalElements: number }>>(`/product/${id}/similar`, { params })
}

/**
 * 收藏商品
 * @param id 商品ID
 * @returns Promise<ApiResponse<{ favorited: boolean }>>
 */
export async function favoriteProduct(id: number | string): Promise<ApiResponse<{ favorited: boolean }>> {
    return request.post<ApiResponse<{ favorited: boolean }>>(`/product/${id}/favorite`)
}

/**
 * 取消收藏商品
 * @param id 商品ID
 * @returns Promise<ApiResponse<{ favorited: boolean }>>
 */
export async function unfavoriteProduct(id: number | string): Promise<ApiResponse<{ favorited: boolean }>> {
    return request.delete<ApiResponse<{ favorited: boolean }>>(`/product/${id}/favorite`)
}

/**
 * 检查商品是否已收藏
 * @param id 商品ID
 * @returns Promise<ApiResponse<{ favorited: boolean }>>
 */
export async function checkProductFavorited(id: number | string): Promise<ApiResponse<{ favorited: boolean }>> {
    return request.get<ApiResponse<{ favorited: boolean }>>(`/product/${id}/favorite`)
}

export default {
    getProducts,
    getUserProducts,
    getProductById,
    createProduct,
    updateProduct,
    deleteProduct,
    updateProductStatus,
    getRecommendedProducts,
    getSimilarProducts,
    favoriteProduct,
    unfavoriteProduct,
    checkProductFavorited
} 